<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>订单管理 - 商户端</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: calc(100vh - 56px);
        }
        .table-success {
            background-color: #d1e7dd;
        }
        .table-success:hover {
            background-color: #c3d9d0;
        }
        .btn-success {
            background-color: #198754;
            border-color: #198754;
        }
        .btn-success:hover {
            background-color: #157347;
            border-color: #146c43;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container-fluid">
        <div class="row">
            <jsp:include page="../common/sidebar.jsp"/>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="pt-3">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h1 class="h2">订单管理</h1>
                    </div>
                    
                    <c:if test="${error != null}">
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            ${error}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </c:if>
                    
                    <!-- 查询表单 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <form action="${pageContext.request.contextPath}/merchant/order" method="get" class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">订单编号</label>
                                    <input type="text" class="form-control" name="orderNo" placeholder="输入订单编号..." value="${orderNo}">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">收货人</label>
                                    <input type="text" class="form-control" name="receiverName" placeholder="输入收货人..." value="${receiverName}">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">收货电话</label>
                                    <input type="text" class="form-control" name="receiverPhone" placeholder="输入收货电话..." value="${receiverPhone}">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div>
                                        <button type="submit" class="btn btn-success w-100">查询</button>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <a href="${pageContext.request.contextPath}/merchant/order" class="btn btn-outline-secondary">重置</a>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- 订单表格 -->
                    <div class="card">
                        <div class="card-body">
                            <div class="mb-3">
                                <button type="button" class="btn btn-danger" id="batchDeleteBtn" onclick="batchDelete()" disabled>批量删除</button>
                                <span class="ms-2 text-muted">已选择 <span id="selectedCount">0</span> 项</span>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-success">
                                        <tr>
                                            <th width="50">
                                                <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                            </th>
                                            <th>订单编号</th>
                                            <th>用户账号</th>
                                            <th>订单金额</th>
                                            <th>订单状态</th>
                                            <th>收货人</th>
                                            <th>收货电话</th>
                                            <th>下单时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <c:choose>
                                            <c:when test="${orders != null && !empty orders}">
                                                <c:forEach var="order" items="${orders}">
                                                    <tr>
                                                        <td>
                                                            <input type="checkbox" class="row-checkbox" value="${order.orderId}" onchange="updateSelectedCount()">
                                                        </td>
                                                        <td>${order.orderNo}</td>
                                                        <td>${order.user != null ? order.user.username : order.userId}</td>
                                                        <td>¥<fmt:formatNumber value="${order.totalAmount}" pattern="#,##0.00"/></td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${order.status == 0}">
                                                                    <span class="badge bg-warning">待付款</span>
                                                                </c:when>
                                                                <c:when test="${order.status == 1}">
                                                                    <span class="badge bg-info">待发货</span>
                                                                </c:when>
                                                                <c:when test="${order.status == 2}">
                                                                    <span class="badge bg-primary">待收货</span>
                                                                </c:when>
                                                                <c:when test="${order.status == 3}">
                                                                    <span class="badge bg-success">已完成</span>
                                                                </c:when>
                                                                <c:when test="${order.status == 4}">
                                                                    <span class="badge bg-danger">已取消</span>
                                                                </c:when>
                                                                <c:when test="${order.status == 5}">
                                                                    <span class="badge bg-secondary">售后中</span>
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <span class="badge bg-secondary">未知</span>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td>${order.receiverName}</td>
                                                        <td>${order.receiverPhone}</td>
                                                        <td><fmt:formatDate value="${order.createTime}" pattern="yyyy-MM-dd HH:mm"/></td>
                                                        <td>
                                                            <a href="${pageContext.request.contextPath}/merchant/order?action=detail&orderId=${order.orderId}" 
                                                               class="btn btn-sm btn-primary">查看详情</a>
                                                            <c:if test="${order.status == 1}">
                                                                <button type="button" class="btn btn-sm btn-success" 
                                                                        onclick="openShipModal(${order.orderId}, '${order.orderNo}')">发货</button>
                                                            </c:if>
                                                        </td>
                                                    </tr>
                                                </c:forEach>
                                            </c:when>
                                            <c:otherwise>
                                                <tr>
                                                    <td colspan="9" class="text-center text-muted">暂无订单数据</td>
                                                </tr>
                                            </c:otherwise>
                                        </c:choose>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页 -->
                            <c:if test="${totalPages > 0}">
                                <nav aria-label="订单分页">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item ${page == 1 ? 'disabled' : ''}">
                                            <a class="page-link" href="${pageContext.request.contextPath}/merchant/order?page=${page - 1}<c:if test='${orderNo != null && !empty orderNo}'>&orderNo=${orderNo}</c:if><c:if test='${receiverName != null && !empty receiverName}'>&receiverName=${receiverName}</c:if><c:if test='${receiverPhone != null && !empty receiverPhone}'>&receiverPhone=${receiverPhone}</c:if>">上一页</a>
                                        </li>
                                        <c:forEach var="i" begin="1" end="${totalPages}">
                                            <li class="page-item ${page == i ? 'active' : ''}">
                                                <a class="page-link" href="${pageContext.request.contextPath}/merchant/order?page=${i}<c:if test='${orderNo != null && !empty orderNo}'>&orderNo=${orderNo}</c:if><c:if test='${receiverName != null && !empty receiverName}'>&receiverName=${receiverName}</c:if><c:if test='${receiverPhone != null && !empty receiverPhone}'>&receiverPhone=${receiverPhone}</c:if>">${i}</a>
                                            </li>
                                        </c:forEach>
                                        <li class="page-item ${page == totalPages ? 'disabled' : ''}">
                                            <a class="page-link" href="${pageContext.request.contextPath}/merchant/order?page=${page + 1}<c:if test='${orderNo != null && !empty orderNo}'>&orderNo=${orderNo}</c:if><c:if test='${receiverName != null && !empty receiverName}'>&receiverName=${receiverName}</c:if><c:if test='${receiverPhone != null && !empty receiverPhone}'>&receiverPhone=${receiverPhone}</c:if>">下一页</a>
                                        </li>
                                    </ul>
                                </nav>
                                <div class="text-center text-muted">
                                    共 ${totalCount} 条记录，第 ${page}/${totalPages} 页
                                </div>
                            </c:if>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- 发货模态框 -->
    <div class="modal fade" id="shipModal" tabindex="-1" aria-labelledby="shipModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="shipModalLabel">订单发货</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="shipForm">
                        <input type="hidden" id="shipOrderId" name="orderId">
                        <div class="mb-3">
                            <label class="form-label">订单编号</label>
                            <input type="text" class="form-control" id="shipOrderNo" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="logisticsCompany" class="form-label">物流公司 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="logisticsCompany" name="logisticsCompany" required>
                            <div class="invalid-feedback">请输入物流公司</div>
                        </div>
                        <div class="mb-3">
                            <label for="logisticsNo" class="form-label">物流单号 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="logisticsNo" name="logisticsNo" required>
                            <div class="invalid-feedback">请输入物流单号</div>
                        </div>
                        <div class="alert alert-danger d-none" id="shipError"></div>
                        <div class="alert alert-success d-none" id="shipSuccess"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-success" id="submitShipBtn" onclick="submitShip()">确认发货</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let shipModal = null;
        
        // 初始化模态框
        document.addEventListener('DOMContentLoaded', function() {
            shipModal = new bootstrap.Modal(document.getElementById('shipModal'));
        });
        
        // 打开发货模态框
        function openShipModal(orderId, orderNo) {
            document.getElementById('shipOrderId').value = orderId;
            document.getElementById('shipOrderNo').value = orderNo;
            document.getElementById('logisticsCompany').value = '';
            document.getElementById('logisticsNo').value = '';
            document.getElementById('shipError').classList.add('d-none');
            document.getElementById('shipSuccess').classList.add('d-none');
            document.getElementById('logisticsCompany').classList.remove('is-invalid');
            document.getElementById('logisticsNo').classList.remove('is-invalid');
            shipModal.show();
        }
        
        // 提交发货
        function submitShip() {
            const orderId = document.getElementById('shipOrderId').value;
            const logisticsCompany = document.getElementById('logisticsCompany').value.trim();
            const logisticsNo = document.getElementById('logisticsNo').value.trim();
            
            // 清除之前的错误状态
            document.getElementById('logisticsCompany').classList.remove('is-invalid');
            document.getElementById('logisticsNo').classList.remove('is-invalid');
            
            const errors = [];
            
            if (!logisticsCompany) {
                errors.push('物流公司');
                document.getElementById('logisticsCompany').classList.add('is-invalid');
            }
            
            if (!logisticsNo) {
                errors.push('物流单号');
                document.getElementById('logisticsNo').classList.add('is-invalid');
            }
            
            if (errors.length > 0) {
                showShipError('请检查以下字段：' + errors.join('、'));
                return;
            }
            
            const submitBtn = document.getElementById('submitShipBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = '发货中...';
            
            document.getElementById('shipError').classList.add('d-none');
            document.getElementById('shipSuccess').classList.add('d-none');
            
            const params = new URLSearchParams();
            params.append('orderId', orderId);
            params.append('logisticsCompany', logisticsCompany);
            params.append('logisticsNo', logisticsNo);
            
            fetch('${pageContext.request.contextPath}/merchant/order/ship', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showShipSuccess(data.message);
                    setTimeout(function() {
                        shipModal.hide();
                        location.reload();
                    }, 1500);
                } else {
                    showShipError(data.message || '发货失败');
                    submitBtn.disabled = false;
                    submitBtn.textContent = '确认发货';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showShipError('发货失败，请重试');
                submitBtn.disabled = false;
                submitBtn.textContent = '确认发货';
            });
        }
        
        function showShipError(message) {
            const errorDiv = document.getElementById('shipError');
            errorDiv.textContent = message;
            errorDiv.classList.remove('d-none');
        }
        
        function showShipSuccess(message) {
            const successDiv = document.getElementById('shipSuccess');
            successDiv.textContent = message;
            successDiv.classList.remove('d-none');
        }
        
        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.row-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            updateSelectedCount();
        }
        
        // 更新选中数量
        function updateSelectedCount() {
            const checkboxes = document.querySelectorAll('.row-checkbox:checked');
            const count = checkboxes.length;
            document.getElementById('selectedCount').textContent = count;
            document.getElementById('batchDeleteBtn').disabled = count === 0;
            
            // 更新全选状态
            const allCheckboxes = document.querySelectorAll('.row-checkbox');
            const selectAll = document.getElementById('selectAll');
            if (allCheckboxes.length === 0) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            } else if (count === allCheckboxes.length) {
                selectAll.checked = true;
                selectAll.indeterminate = false;
            } else if (count > 0) {
                selectAll.checked = false;
                selectAll.indeterminate = true;
            } else {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            }
        }
        
        // 批量删除
        function batchDelete() {
            const checkboxes = document.querySelectorAll('.row-checkbox:checked');
            if (checkboxes.length === 0) {
                alert('请选择要删除的订单');
                return;
            }
            
            const orderIds = Array.from(checkboxes).map(cb => cb.value);
            if (!confirm('确定要删除选中的 ' + orderIds.length + ' 个订单吗？此操作不可恢复！')) {
                return;
            }
            
            const params = new URLSearchParams();
            params.append('action', 'batchDelete');
            orderIds.forEach(id => {
                params.append('orderIds[]', id);
            });
            
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            batchDeleteBtn.disabled = true;
            batchDeleteBtn.textContent = '删除中...';
            
            fetch('${pageContext.request.contextPath}/merchant/order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.message || '删除失败');
                    batchDeleteBtn.disabled = false;
                    batchDeleteBtn.textContent = '批量删除';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请重试');
                batchDeleteBtn.disabled = false;
                batchDeleteBtn.textContent = '批量删除';
            });
        }
        
        // 初始化选中数量
        document.addEventListener('DOMContentLoaded', function() {
            updateSelectedCount();
        });
    </script>
</body>
</html>

